use loco_rs::prelude::*;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

pub use super::_entities::notifications::{self, ActiveModel, Entity, Model};

#[derive(Debug, Deserialize, Serialize)]
pub struct CreateParams {
    pub r#type: String,
    pub notifiable_type: String,
    pub notifiable_id: String,
    pub data: String,
}

#[derive(Debug, Validate, Deserialize)]
pub struct Validator {
    #[validate(length(min = 1, message = "Type must not be empty."))]
    pub r#type: String,
    #[validate(length(min = 1, message = "Notifiable type must not be empty."))]
    pub notifiable_type: String,
    #[validate(length(min = 1, message = "Notifiable ID must not be empty."))]
    pub notifiable_id: String,
    #[validate(length(min = 1, message = "Data must not be empty."))]
    pub data: String,
}

impl Validatable for ActiveModel {
    fn validator(&self) -> Box<dyn Validate> {
        Box::new(Validator {
            r#type: self.r#type.as_ref().to_owned(),
            notifiable_type: self.notifiable_type.as_ref().to_owned(),
            notifiable_id: self.notifiable_id.as_ref().to_owned(),
            data: self.data.as_ref().to_owned(),
        })
    }
}

#[async_trait::async_trait]
impl ActiveModelBehavior for super::_entities::notifications::ActiveModel {
    async fn before_save<C>(self, _db: &C, insert: bool) -> Result<Self, DbErr>
    where
        C: ConnectionTrait,
    {
        self.validate()?;
        if insert {
            let mut this = self;
            this.id = ActiveValue::Set(Uuid::new_v4().to_string());
            Ok(this)
        } else {
            Ok(self)
        }
    }
}

impl Model {
    /// finds a notification by the provided id
    ///
    /// # Errors
    ///
    /// When could not find notification or DB query error
    pub async fn find_by_id(db: &DatabaseConnection, id: &str) -> ModelResult<Self> {
        let notification = notifications::Entity::find()
            .filter(
                model::query::condition()
                    .eq(notifications::Column::Id, id)
                    .build(),
            )
            .one(db)
            .await?;
        notification.ok_or_else(|| ModelError::EntityNotFound)
    }

    /// finds notifications by the provided notifiable id and type
    ///
    /// # Errors
    ///
    /// When could not find notifications or DB query error
    pub async fn find_by_notifiable(
        db: &DatabaseConnection,
        notifiable_type: &str,
        notifiable_id: &str,
    ) -> ModelResult<Vec<Self>> {
        let notifications = notifications::Entity::find()
            .filter(
                model::query::condition()
                    .eq(notifications::Column::NotifiableType, notifiable_type)
                    .eq(notifications::Column::NotifiableId, notifiable_id)
                    .build(),
            )
            .all(db)
            .await?;
        Ok(notifications)
    }

    /// Asynchronously creates a notification and saves it to the database.
    ///
    /// # Errors
    ///
    /// When could not save the notification into the DB
    pub async fn create(db: &DatabaseConnection, params: &CreateParams) -> ModelResult<Self> {
        let notification = notifications::ActiveModel {
            r#type: ActiveValue::set(params.r#type.to_string()),
            notifiable_type: ActiveValue::set(params.notifiable_type.to_string()),
            notifiable_id: ActiveValue::set(params.notifiable_id.to_string()),
            data: ActiveValue::set(params.data.to_string()),
            ..Default::default()
        }
        .insert(db)
        .await?;

        Ok(notification)
    }
}

impl ActiveModel {
    /// Marks the notification as read
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn mark_as_read(mut self, db: &DatabaseConnection) -> ModelResult<Model> {
        self.read_at = ActiveValue::set(Some(chrono::Utc::now().into()));
        Ok(self.update(db).await?)
    }

    /// Marks the notification as unread
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn mark_as_unread(mut self, db: &DatabaseConnection) -> ModelResult<Model> {
        self.read_at = ActiveValue::set(None);
        Ok(self.update(db).await?)
    }
}
